package com.example.rabbitmq_study.topic;

import com.example.rabbitmq_study.util.RabbitmqUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeoutException;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/7/29 9:41
 */
public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //获取连接对象
        Connection connection = RabbitmqUtil.getConnection();

        //获取连接中的通道
        Channel channel = connection.createChannel();

        //声明临时队列，获取临时队列名称
        String queueName = channel.queueDeclare().getQueue();

        /*
            绑定交换机和临时队列
                参数1：临时队列名称
                参数2：交换机名称
                参数3：路由key
         */
        channel.queueBind(queueName, "topics", "#.user.*");

        //接收处理消息
        channel.basicConsume(queueName, false, new DefaultConsumer(channel){
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    //获取交换机
                    String exchange = envelope.getExchange();
                    //消息id，mq在channel中用来标识消息的id，如果获取到该id表明也获取到了该id的消息所以可用于确认消息已接收
                    long deliveryTag = envelope.getDeliveryTag();
                    //将字节类型的消息转换成字符串
                    String string = new String(body, "utf-8");

                    System.out.println("consumer1 receive exchange:" + exchange);
                    System.out.println("consumer1 receive deliveryTag:" + deliveryTag);
                    System.out.println("consumer1 receive message:" + string);

                    //正常运行手动确认
                    channel.basicAck(envelope.getDeliveryTag()/*消息ID*/, false/*批量确认*/);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    //异常则手动确认，将消息返回队列
                    channel.basicNack(envelope.getDeliveryTag()/*消息ID*/, false/*批量确认*/, true/*返回队列*/);
                }
            }
        });
    }

}
